<template>
  <a-modal v-model:open="visible" :maskClosable="false" v-bind="$attrs" @cancel="handleClosed" :width="600">
    <template #title>
      <span>{{ vtitle }}</span>
      <div class="flex-row" style="margin-top: 10px; width: 100%; display: flex">
        <div class="title-header" style="min-width: 0px; margin-left: 0px">
          <span class="file-header" style="color: rgb(30, 136, 229)" @click="handPathClick(null)">全部文件</span>
          <span v-for="item in folderPathList" :key="item.fileId" class="file-header" style="color: rgb(30, 136, 229)" @click="handPathClick(item)">
            {{ '/' + item.fileName }}
          </span>
        </div>
        <div class="operation">
          <span class="folder-search" @click="handleShowSearchInputClick">
            <a-input
              ref="seachFolderInput"
              placeholder="请输入文件名称并回车"
              type="text"
              class="ant-input search-folder animated"
              v-model:value="searchInputVlaue"
              :style="searchInputStyle"
              @blur="handleSearchInputBlur"
              @pressEnter="handleSearchInputEnter"
            />
            <Icon icon="ant-design:search-outlined" class="icon-search-folder" style="font-size: 16px; display: inline-flex" />
          </span>
          <span class="icon-create-folder" @click="handleAddFolderClick">
            <Icon icon="ant-design:folder-add-outlined" class="icon-search-folder" style="font-size: 16px; display: inline-flex" />
          </span>
        </div>
      </div>
    </template>

    <div class="ant-spin-nested-loading">
      <div class="ant-spin-container">
        <div class="folder-content">
          <div class="folder-node">
            <ul class="text-list">
              <li v-if="isShowAddFolderInput" class="text-item text-item-back">
                <Icon icon="ant-design:folder-outlined" class="icon-type" style="font-size: 16px; color: rgb(253, 202, 7); display: inline-flex" />
                <a-input v-model:value="newInputVlaue" class="add-folder-input" @blur="handleNewFolderInputBlur" />
                <span class="text-name ellipsis">{{ newInputVlaue }}</span>
              </li>
              <li
                v-for="item in folderDataList"
                :key="item.fileId"
                :class="item.fileId == selectedFileId ? 'text-item text-item-back' : 'text-item'"
                @click="handleFolderClick(item)"
              >
                <Icon icon="ant-design:folder-outlined" class="icon-type" style="font-size: 16px; color: rgb(253, 202, 7); display: inline-flex" />
                <span class="text-name ellipsis" @click="handleFileNameClick(item)">{{ item.fileName }}</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <a-button @click="handleClosed">关 闭</a-button>
      <a-button type="primary" @click="handleOk">确 定</a-button>
    </template>
  </a-modal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, computed } from 'vue';
  import { useUserStore } from '/@/store/modules/user';
  import { saveOrUpdate, searchFolder } from '../files.api';
  import { cloneDeep } from 'lodash-es';
  import { message } from 'ant-design-vue';

  export default defineComponent({
    name: 'FolderSelectModal',
    emits: ['closed', 'success'],
    setup(props, { emit }) {
      const userStore = useUserStore();
      //当前用户ID
      const userId = userStore.getUserInfo.id;

      const seachFolderInput = ref();

      //弹窗显隐标记
      const visible = ref(false);
      //目录路径列表
      const folderPathList: any = ref([]);
      //标题
      const vtitle = ref('上传到');
      //搜索输入框样式
      const searchInputStyle = ref({});
      const searchInputVlaue = ref('');
      //目录列表中新建目录名
      const newInputVlaue = ref('');
      const isShowAddFolderInput = ref(false);
      //目录列表数据
      const folderDataList: Array = ref([]);
      //选中目录ID
      const selectedFileId = ref('');
      //过滤的目录ID
      const fliterFileIds = ref('');

      /**
       * 显示modal
       * title: 标题
       * pathList: 当前目录路径
       * fileIds: 过滤的目录IDS
       */
      function showModal(title, pathList, fileIds) {
        visible.value = true;
        vtitle.value = title;
        searchInputStyle.value = { width: '0px' };
        selectedFileId.value = '';
        folderPathList.value = pathList;
        folderDataList.value = [];
        fliterFileIds.value = fileIds ? fileIds : '';
        loadSubFolderList();
      }

      function handleShowSearchInputClick() {
        searchInputStyle.value = { width: '150px' };
        seachFolderInput.value.focus();
      }

      function handleSearchInputBlur() {
        searchInputStyle.value = { width: '0px' };
        searchInputVlaue.value = '';
      }

      function handleSearchInputEnter() {
        loadSubFolderList();
      }

      function handleAddFolderClick() {
        isShowAddFolderInput.value = true;
      }

      async function handleNewFolderInputBlur() {
        isShowAddFolderInput.value = false;
        if (!newInputVlaue.value) {
          return;
        }
        const parentId = folderPathList.value && folderPathList.value.length > 0 ? folderPathList.value[folderPathList.value.length - 1].fileId : '';
        await saveOrUpdate(
          {
            delFlag: '0',
            fileName: newInputVlaue.value,
            fileType: 'folder',
            isFolder: '1',
            parentId: parentId,
            storeType: 'manage',
          },
          false
        );
        await loadSubFolderList();
      }

      /**
       * 目录路径点击事件
       */
      async function handPathClick(item) {
        //移除当前目录路径下的子路径
        if (item) {
          let index = folderPathList.value.findIndex((p) => {
            return p.fileId == item.fileId;
          });
          folderPathList.value.splice(index + 1);
        } else {
          folderPathList.value = [];
        }
        //加载当前目录下的子目录
        await loadSubFolderList();
      }

      async function handleFolderClick(item) {
        selectedFileId.value = item.fileId;
      }

      async function handleFileNameClick(item) {
        folderPathList.value.push(item);
        loadSubFolderList();
      }

      //关闭后的回调
      function handleClosed() {
        visible.value = false;
        emit('closed');
      }

      function handleOk() {
        if (folderPathList.value && folderPathList.value.length == 0) {
          message.warn('请选择一个文件夹');
          return;
        }
        let pathList = cloneDeep(folderPathList.value);
        visible.value = false;
        emit('success', pathList);
      }

      /**
       * 加载目录列表
       */
      async function loadSubFolderList() {
        let parentId = '';
        if (folderPathList.value && folderPathList.value.length > 0) {
          parentId = folderPathList.value[folderPathList.value.length - 1].fileId;
        }
        let seachText = searchInputVlaue.value;
        const data = await searchFolder({
          parentId: parentId,
          searchText: seachText,
        });
        folderDataList.value = [];
        data.forEach((p) => {
          let hasFliter = unref(fliterFileIds.value)
            .split(',')
            .filter((id) => id == p.id);
          if (unref(hasFliter).length == 0) {
            folderDataList.value.push({
              fileId: p.id,
              fileName: p.fileName,
            });
          }
        });
      }

      return {
        folderPathList,
        seachFolderInput,
        visible,
        vtitle,
        searchInputStyle,
        searchInputVlaue,
        newInputVlaue,
        isShowAddFolderInput,
        folderDataList,
        selectedFileId,
        showModal,
        handleClosed,
        handleOk,
        handleShowSearchInputClick,
        handleSearchInputBlur,
        handleSearchInputEnter,
        handleNewFolderInputBlur,
        handPathClick,
        handleFolderClick,
        handleFileNameClick,
        handleAddFolderClick,
      };
    },
  });
</script>

<style lang="less" scoped>
  @import '../less/FolderSelect';
</style>
